package com.qiangesoft.weather.juhe;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qiangesoft.weather.juhe.constant.JuheWeatherConstant;
import com.qiangesoft.weather.juhe.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 聚合天气数据
 * <p>
 * 参考：https://www.juhe.cn/docs/api/id/73
 *
 * @author qiangesoft
 * @date 2024-01-08
 */
@Slf4j
@Component
public class JuheWeatherTask {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 每隔一小时执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void pullData() {
        log.info("Pull data begin==================>");
        long startTime = System.currentTimeMillis();

        // 拉取天气
        this.saveWeather("北京");

        // 拉取生活指数
        this.saveShzs("北京");

        // 拉取天气种类
        this.saveWeatherCategory("北京");

        // 拉取城市列表
        this.saveCity("北京");

        long endTime = System.currentTimeMillis();
        log.info("spend time:" + (endTime - startTime));
        log.info("Pull data end<==================");
    }

    /**
     * 天气预报
     *
     * @param city
     */
    private void saveWeather(String city) {
        StringBuilder sendUrl = new StringBuilder(JuheWeatherConstant.TQ_URL)
                .append("?key=").append(JuheApi.KEY_VALUE)
                .append("&city=").append(city);
        ResponseEntity<JuheResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), JuheResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Juhe interface error");
            return;
        }

        // 请求失败
        JuheResult juheResult = responseEntity.getBody();
        Integer code = juheResult.getError_code();
        if (code != 0) {
            log.info("Request for Juhe interface failed");
            return;
        }

        Object juheWeather = juheResult.getResult();
        if (juheWeather == null) {
            return;
        }

        String string = JSONObject.toJSONString(juheWeather);
        log.info(string);

        // todo 入库
        JuheWeather weather = JSONObject.parseObject(string, JuheWeather.class);
    }

    /**
     * 生活指数
     *
     * @param city
     */
    private void saveShzs(String city) {
        StringBuilder sendUrl = new StringBuilder(JuheWeatherConstant.SH_URL)
                .append("?key=").append(JuheApi.KEY_VALUE)
                .append("&city=").append(city);
        ResponseEntity<JuheResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), JuheResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Juhe interface error");
            return;
        }

        // 请求失败
        JuheResult juheResult = responseEntity.getBody();
        Integer code = juheResult.getError_code();
        if (code != 0) {
            log.info("Request for Juhe interface failed");
            return;
        }

        Object juheLife = juheResult.getResult();
        if (juheLife == null) {
            return;
        }

        String string = JSONObject.toJSONString(juheLife);
        log.info(string);

        // todo 入库
        JuheLife life = JSONObject.parseObject(string, JuheLife.class);
    }

    /**
     * 天气种类
     *
     * @param city
     */
    private void saveWeatherCategory(String city) {
        StringBuilder sendUrl = new StringBuilder(JuheWeatherConstant.ZL_URL)
                .append("?key=").append(JuheApi.KEY_VALUE)
                .append("&city=").append(city);
        ResponseEntity<JuheResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), JuheResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Juhe interface error");
            return;
        }

        // 请求失败
        JuheResult juheResult = responseEntity.getBody();
        Integer code = juheResult.getError_code();
        if (code != 0) {
            log.info("Request for Juhe interface failed");
            return;
        }

        Object juheWeatherCategoryList = juheResult.getResult();
        if (ObjectUtils.isEmpty(juheWeatherCategoryList)) {
            return;
        }

        String string = JSONObject.toJSONString(juheWeatherCategoryList);
        log.info(string);

        // todo 入库
        List<JuheWeatherCategory> weatherCategoryList = JSONArray.parseArray(string, JuheWeatherCategory.class);
    }

    /**
     * 城市
     *
     * @param city
     */
    private void saveCity(String city) {
        StringBuilder sendUrl = new StringBuilder(JuheWeatherConstant.CS_URL)
                .append("?key=").append(JuheApi.KEY_VALUE)
                .append("&city=").append(city);
        ResponseEntity<JuheResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), JuheResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Juhe interface error");
            return;
        }

        // 请求失败
        JuheResult juheResult = responseEntity.getBody();
        Integer code = juheResult.getError_code();
        if (code != 0) {
            log.info("Request for Juhe interface failed");
            return;
        }

        Object juheCityList = juheResult.getResult();
        if (ObjectUtils.isEmpty(juheCityList)) {
            return;
        }

        String string = JSONObject.toJSONString(juheCityList);
        log.info(string);

        // todo 入库
        List<JuheCity> cityList = JSONArray.parseArray(string, JuheCity.class);
    }
}